package cn.fuxi2022.auth.controller;

import cn.fuxi2022.auth.service.AppletsService;
import cn.fuxi2022.auth.service.GroupStudentService;
import cn.fuxi2022.core.model.vo.auth.AppletsLoginRegisterVo;
import cn.fuxi2022.model.resp.R;
import cn.fuxi2022.core.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/applets")
public class AppletsLoginAndRegisterController {

    @Autowired
    private AppletsService appletsService;

    @Autowired
    private GroupStudentService groupStudentService;

    /**
     * 微信获取手机号
     *
     * @param code 微信小程序前端获取的验证码code
     * @return 手机号
     */
    @GetMapping("/getPhoneByCode/{code}")
    public R getPhoneByCode(@PathVariable("code") String code) {
        String phone = appletsService.getPhoneByCode(code);
        if (!StringUtils.hasText(phone)) {
            return R.error("手机号获取失败，请再重新试一下吧");
        }
        return R.ok().data("phone", phone);
    }

    /**
     * 根据手机号获取验证码
     *
     * @param appletsLoginRegisterVo 微信小程序前端登录表单（填写了手机号）
     * @return 验证码发送成功
     */
    @PostMapping("/sendCaptcha")
    public R sendCaptcha(
            @RequestBody @Validated(AppletsLoginRegisterVo.CaptchaVoCheck.class)
            AppletsLoginRegisterVo appletsLoginRegisterVo) {

        appletsService.getCaptcha(appletsLoginRegisterVo.getPhone());

        return R.ok("验证码发送成功");
    }

    /**
     * 登录方法
     *
     * @param appletsLoginRegisterVo 微信小程序前端登录表单（填写了手机号）
     * @return 验证码发送成功
     */
    @PostMapping("/login/{code}")
    public R login(
            @RequestBody @Validated(AppletsLoginRegisterVo.LoginVoCheck.class)
            AppletsLoginRegisterVo appletsLoginRegisterVo,
            @PathVariable("code") String code
    ) {
        Map<String, Object> map = appletsService.login(appletsLoginRegisterVo.getPhone(), appletsLoginRegisterVo.getCaptcha(), code);
        return R.ok().data(map);
    }


    /**
     * 获取当前用户信息
     *
     * @return 当前token的用户信息
     */
    @GetMapping("/info")
    public R getInfo(HttpServletRequest request) {
        String id = JwtUtils.getMemberIdByJwtToken(request);
        return R.ok().data(groupStudentService.getById(id));
    }
}
